<?php
/**
 * ***********************************************************************************
 * 咨询鲤 PC端知识店铺-课程相关
 * 
 * @author Mr.RJH
 * @date 2025-09-09
 * @email<15213026209@163.com>
 * ***********************************************************************************
 */
namespace app\controller;

use app\BaseController;

use app\model\merchant\ConfigModel;
use app\model\product\ZxlKnowStoreProductModel;
use app\model\product\ZxlKnowStoreProductAttrModel;
use app\model\product\ZxlKnowStoreCategoryModel;
use app\model\product\ZxlKnowStoreCourseCatalogModel;
use app\model\product\ZxlKnowStoreCourseContentModel;

use app\model\user\ZxlKnowStoreCollectModel;
use app\model\user\ZxlKnowStorePowerModel;

use app\service\ProductService;
class Course extends BaseController
{
    /**
     * 课程列表
     * 
     * @return mixed
     */
    public function index()
    {
        if ($this->request->isPost()) {

            $limit = $this->request->param('limit', 10);
            $page = $this->request->param('page',1);
            $cate_level = $this->request->param('cate_level', 2); // 分类等级
            $cate_id = $this->request->param('category_id', '');

            $m_id = $this->request->m_id;
            try {
                $productService = new ProductService($m_id);
                $list = $productService->get_product_list(3, $limit, $page, $cate_id, $cate_level);
                foreach ($list['data'] as &$v) {
                    $v['head_imgs'] = $v['head_imgs'] ? explode(',',$v['head_imgs'])[0] : '/static/images/no_pic_1.png';
                    $v['tags'] = ZxlKnowStoreProductModel::get_tag_list($v['tags']);
                    // 总课时
                    $v['class_hour'] = ZxlKnowStoreCourseContentModel::where('product_id', $v['id'])->count();
                    if ($v['p_product_id']) {
                        $v['class_hour'] = ZxlKnowStoreCourseContentModel::where('product_id', $v['p_product_id'])->count();
                    }
                }
                
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => 'SUCCESS','count' => $list['total'],'data' => $list['data']]);
        }

        // 获取分类
        $first_category = ZxlKnowStoreCategoryModel::first_category($this->request->m_id, 2);
        
        $this->assign('first_category', $first_category);
        return $this->fetch();
    }

    /**
     * 获取二级分类
     * 
     * @return mixed
     */
    public function get_second_category()
    {
        if ($this->request->isPost()) {
            $p_id = $this->request->post('p_id');
            try {
                if ($p_id == 0) {
                    return json(['code' => 0,'msg' => 'SUCCESS', 'data' => []]);
                }
                $info = ZxlKnowStoreCategoryModel::find($p_id);
                if (!$info) {
                    return json(['code' => 1,'msg' => '分类错误，请刷新页面重试']);
                }
                $list = ZxlKnowStoreCategoryModel::second_category($this->request->m_id, $p_id);
                return json(['code' => 0,'msg' => 'SUCCESS', 'data' => $list]);
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            
        }
        
    }

    /**
     * 课程详情
     * 
     * @return mixed
     */
    public function detail()
    {
        $id = $this->request->param('id');
        $info = ZxlKnowStoreProductModel::getInfo($this->request->m_id, $id);
        if (!$info) {
            return redirect('/error/http404');
        }
        if ($info) {
            $info->visit_num += 1; // 增加访问量
            $info->save();

            $info['head_imgs'] = explode(',', $info['head_imgs']);
            if ($info['tags']) {
                $info['tags'] = json_decode($info['tags'], true);
            }
            $info['attr'] = ZxlKnowStoreProductAttrModel::where(['product_id' => $info['id'], 'status' => 1, 'is_delete' => 0])->order('sale_price asc')->select()->toArray();

            // 是否收藏
            $info['is_favorites'] = 0;
            $favorites = ZxlKnowStoreCollectModel::where(['user_id' => $this->user_id, 'product_id' => $info['id']])->find();
            if ($favorites) {
                $info['is_favorites'] = 1;
            }

            // 总课时
            $info['class_hour'] = ZxlKnowStoreCourseContentModel::where('product_id', $info['id'])->count();
            if ($info['p_product_id']) {
                $info['class_hour'] = ZxlKnowStoreCourseContentModel::where('product_id', $info['p_product_id'])->count();
            }

            // 课程内容
            $catalog = ZxlKnowStoreCourseCatalogModel::where('product_id', ZxlKnowStoreProductModel::getMainProductId($id))->field('id,name')->order('sort', 'asc')->select()->toArray();
            if ($catalog) {
                foreach ($catalog as &$v) {
                    $children = ZxlKnowStoreCourseContentModel::where(['catalog_id' => $v['id'],'product_id' => ZxlKnowStoreProductModel::getMainProductId($id)])->order(['sort' => 'desc', 'id' => 'asc'])->select()->toArray();
                    $v['count'] = count($children);
                    foreach ($children as &$value) {
                        if ($value['time']) {
                            $value['time'] = show_time_format($value['time']);
                        }
                    }
                    $v['children'] = $children;
                }
            } else {
                $catalog = ZxlKnowStoreCourseContentModel::where(['product_id' => ZxlKnowStoreProductModel::getMainProductId($id)])->order(['sort' => 'desc', 'id' => 'asc'])->select()->toArray();
                foreach ($catalog as &$value) {
                    if ($value['time']) {
                        $value['time'] = show_time_format($value['time']);
                    }
                }
            }
            $info['catalog'] = $catalog;

            // 是否购买
            $info['is_buy'] = ZxlKnowStorePowerModel::getPowerDetail($info['id'], $this->user_id);
            if ($info['is_buy'] == 1) {
                $info['content_id'] = ZxlKnowStoreCourseContentModel::where(['product_id' => ZxlKnowStoreProductModel::getMainProductId($id)])->order(['id' => 'asc'])->value('id');
            }
        }

        // 购课须知
        $notice = ConfigModel::getConfigValue('notice')[1];
        
        $productService = new ProductService($this->request->m_id);
        // 相关课程
        $related_list = $productService->rand_recommend_product(10, 3);

        $this->assign('notice', $notice);
        $this->assign('info', $info);
        $this->assign('related_list', $related_list);

        return $this->fetch();
    }

    /**
     * 课程学习
     * 
     * @return mixed
     */
    public function study()
    {
        $content_id = $this->request->param('content_id');
        $product_id = $this->request->param('product_id');

        // 是否购买课程
        $is_buy = ZxlKnowStorePowerModel::getPowerDetail($product_id, $this->user_id);
        // 课程信息
        $product = ZxlKnowStoreProductModel::getInfo($this->request->m_id, $product_id, $is_buy);
        
        // 课程内容信息
        $info = ZxlKnowStoreCourseContentModel::alias('c')->where(['c.id' => $content_id])->leftJoin('zxl_material m','c.material_id = m.id')->field('c.*,m.text_content')->find();
        if (!$product || !$info) {
            return redirect('/error/http404');
        }
        $product['head_imgs'] = explode(',', $product['head_imgs']);
        // 总课时
        $product['class_hour'] = ZxlKnowStoreCourseContentModel::where('product_id', $product_id)->count();
        if ($product['p_product_id']) {
            $product['class_hour'] = ZxlKnowStoreCourseContentModel::where('product_id', $product['p_product_id'])->count();
        }
        // 课程目录
        $catalog = ZxlKnowStoreCourseCatalogModel::where('product_id', ZxlKnowStoreProductModel::getMainProductId($product_id)
        )->field('id,name')->order('sort', 'asc')->select()->toArray();
        if ($catalog) {
            foreach ($catalog as &$v) {
                $children = ZxlKnowStoreCourseContentModel::where(['catalog_id' => $v['id'],'product_id' => ZxlKnowStoreProductModel::getMainProductId($product_id)])->order(['sort' => 'desc', 'id' => 'asc'])->select()->toArray();
                $v['count'] = count($children);
                foreach ($children as &$value) {
                    if ($value['time']) {
                        $value['time'] = show_time_format($value['time']);
                    }
                }
                $v['children'] = $children;
            }
        } else {
            $catalog = ZxlKnowStoreCourseContentModel::where(['product_id' => ZxlKnowStoreProductModel::getMainProductId($product_id)])->order(['sort' => 'desc', 'id' => 'asc'])->select()->toArray();
            foreach ($catalog as &$value) {
                if ($value['time']) {
                    $value['time'] = show_time_format($value['time']);
                }
            }
        }
        
        if ($info['time']) {
            $info['time'] = show_time_format($info['time']);
        }
        $info['is_buy'] = $is_buy;

        $this->assign('catalog', $catalog);
        $this->assign('product', $product);
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 验证是否具有学习权限
     * 
     * @return json
     */
    public function study_verify_auth()
    {
        if ($this->request->isPost()) {

            $product_id = $this->request->param('product_id');
            $content_id = $this->request->param('content_id');
            try {
                // 是否购买课程
                $is_buy = ZxlKnowStorePowerModel::getPowerDetail($product_id, $this->user_id);

                // 课程内容信息
                $info = ZxlKnowStoreCourseContentModel::find($content_id);
                if ($info['is_see'] == 1) { // 是否试看
                    $is_buy = 1;
                }
            } catch (\Exception $e) {
                return json(['code' => 1,'msg' => $e->getMessage()]);
            }
            return json(['code' => 0,'msg' => 'SUCCESS', 'data' => $is_buy]);
        }
        
    }
}